<template>
	<uv-popup ref="popup" mode="bottom" bgColor="#F3F4F5" :custom-style="{height: '100vh'}">
		<view class="content text-df">
			<view class="flexBox">
				<view class="search-warp">
					<view class="area">
						<text>{{currentAddress && currentAddress.ad_info.city}}</text>
						<view class="triangle"></view>
					</view>
					<view class="search">
						<uni-text data-v-2ddb064c="" style="margin-right: 10upx;"
							class="lg text-gray cuIcon-search"><span></span></uni-text>
						<input style="width: 90%;min-height: 50rpx;font-size: 28rpx;line-height: 50rpx;" type="text"
							placeholder="搜索地点" :value="searchKey" @input="search" />
					</view>
					<view class="" @click="closeCircle">
						<uni-text data-v-2ddb064c="" v-if="empty"
							class="lg text-gray cuIcon-roundclose"><span></span></uni-text>
					</view>
				</view>
			</view>
			<scroll-view scroll-y="true" class="option" v-show="IsOption">
				<view class='column_item' v-for='(item,index) in searchData' :key='index' @click="tapOption(item)">
					{{item.title}}
					<view style="font-size: 12px;color: #ccc;">
						{{item.address}}
					</view>
				</view>
			</scroll-view>
			<view>
				<view class="page-section page-section-gap">
					<view class="center-icon">
						<view class="pst-c">
							<view class="pst-l"></view>
						</view>
					</view>

					<map id="myMap" style="width: 100%; height: 600rpx;" :latitude="latitude" :longitude="longitude"
						:show-location="true" :scale="mapScale" @poitap="poitap"
						:enable-zoom="true" @regionchange="regionchange"></map>

				</view>
			</view>
			<view class="select-wrap">
				<view class="select-adderss">
					<view class="s-a-info">
						<text class="s-a-t1 f-c-6">当前地址</text>
						<text class="s-a-t2 text-bold">{{currentAddress && currentAddress.title || ''}}</text>
						<text class="s-a-t2 f-c-9">{{currentAddress && currentAddress.address || ''}}</text>
					</view>
					<view class="s-a-but" @click="handleGoBack">
						使用地址
					</view>
				</view>
				<view class="list-wrap">
					<view class="flex justify-between">
						<text class="l-t-title f-c-6">附近地址</text>
						<text class="text-red" @click="close">取消</text>
					</view>
					<scroll-view scroll-y="" style="height: 700rpx;">
						<view class="list" v-for="(item, index) in poitList" :key="index" @click="handleSelect(index)">
							<view class="simple-dots" :class="{dots: index === activate}"></view>
							<view class="info">
								<text class="l-i-title text-600">{{item.title}}</text>
								<text class="l-i-detail ">{{item.address}}</text>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>

		</view>
	</uv-popup>
</template>


<script>
	// import tools from "@/commons/tools";
	import QQMapWX from '@/static/js/qqmap-wx-jssdk.min.js';
	// import QQMapWXH5 from '@/static/js/qqmap-wx-jssdk.minH5.js'
	var self, mapCtx
	var qqmapsdk
	export default {
		props: {
			// coordinate: {
			//   type: Object,
			//   default: () => {}
			// },
		},
		//相关配置参数
		data() {
			return {
				loading: false,
				mapScale: 16,
				coordinate: {
					latitude: 22.83393,
					longitude: 108.31343
				},
				// 初始化的中心位置
				latitude: '',
				longitude: '',
				// 标记点
				markers: [{
					id: 1,
					latitude: '',
					longitude: '',
					name: '',
				}],
				poitList: [], // 周边地址
				choosePoitFlag: -1,
				searchData: [],
				IsOption: false,
				searchKey: "",
				empty: false,
				tapOpitItem: {},
				pageIndex: 1,
				activate: null,
				current: {},
				currentAddress: {},
				mapshow: true,
				marker: null,
				mapH5: null,
				clickAddress: null,
				allowCity: null
			}

		},
		created() {
			uni.$uv.http.get('/system/dict/data/type/allow_city').then(res => {
				this.allowCity = res.data.map(item => (item.dictValue)).join(',')
			})
		},
		mounted() {
			self = this
			// 获取当前map
			mapCtx = uni.createMapContext('myMap', self)

			qqmapsdk = new QQMapWX({
				key: this.$hd.mapKey
				// '4CCBZ-RUDCB-Q4GUJ-NZXBJ-4GVQ7-OFFEY' : 'HAABZ-CNBCL-EKWP2-MAGP2-7RQFF-TTFGA'
			})

			mapCtx.on("", (e) => {
				console.log("markerClusterCreate", e);
			});

		},
		methods: {
			regionchange(e) {
				console.log('e', e)
				console.log('this.latitude', this.latitude)
				if (e.causedBy=="drag"&& e.type == "end") {
					const latitude = e.detail.centerLocation.latitude
					const longitude = e.detail.centerLocation.longitude
					// this.getLocationInfo()
					this.clickAddress = null
					this.currentAddress = {}
					// this.toLocation({latitude: this.latitude, longitude: this.longitude})
					this.mapRange(latitude, longitude)
				}
			},
			open(data) {
				this.$refs.popup.open();
				// data.lat  = 22.83393
				// data.lng =108.31343
				this.latitude = data.lat //22.83393
				this.longitude = data.lng //108.31343
				// this.markers[0].longitude = data.lng
				// this.markers[0].latitude = data.lat
				this.currentAddress.latitude = data.lat
				this.currentAddress.longitude = data.lng
				// this.currentAddress.address = data.address
				
				// if (this.coordinate.latitude && this.coordinate.longitude) {
				// 	this.latitude = this.coordinate?.latitude
				// 	this.longitude = this.coordinate?.longitude
				// 	this.markers[0].longitude = this.coordinate?.longitude
				// 	this.markers[0].latitude = this.coordinate?.latitude
				// 	this.currentAddress = this.coordinate
				// }

				this.getAuthorizeInfo()
				// this.getLocationInfo()
			},
			close() {
				this.$refs.popup.close();
			}, //创建marker事件
			createMarker(lat, lng) {
				console.log(self.marker, "self.marker")
				if (!self.marker) {
					self.marker = new TMap.MultiMarker({
						id: 'marker-layer',
						map: self.mapH5,
						styles: {
							"marker": new TMap.MarkerStyle({
								"width": 25,
								"height": 35,
								"anchor": {
									x: 16,
									y: 32
								},
								"src": 'https://mapapi.qq.com/lbs/javascriptGL/demo/img/markerDefault.png'
							})
						},
						geometries: [{
							"id": 'demo',
							"styleId": 'marker',
							"position": new TMap.LatLng(lat || self.latitude, lng || self.longitude),
							"properties": {
								"title": "marker"
							}
						}]
					});
				}
			},
			//移除marker事件
			removeMarker() {
				if (self.marker) {
					self.marker.setMap(null);
					self.marker = null;
				}
			},
			// 位置授权
			getAuthorizeInfo() {
				try {
					uni.authorize({
						scope: 'scope.userLocation',
						success() { // 允许授权
							console.log("确定了")
							self.getLocationInfo();
						},
						fail() { // 拒绝授权
							self.openConfirm();
							console.log("你拒绝了授权，无法获得周边信息")
						}
					})
				} catch (err) {
					self.getLocationInfo();
				}

			},
			// 获取当前地理位置
			getLocationInfo() {
				// console.log(self.latitude, self.longitude, "self.latitude")
				this.loading = true
				if (this.latitude && this.longitude) {
					this.mapRange(this.latitude, this.longitude)
					this.loading = false
					return
				}
				uni.getLocation({
					type: 'wgs84',
					geocode: true,
					isHighAccuracy: true,
					altitude: true,
					success(res) {
						self.loading = false
						console.log(res, "当前位置");

						// 移动到当前位置
						self.toLocation(res)
						self.latitude = res.latitude;
						self.longitude = res.longitude;
						self.mapRange(res.latitude, res.longitude)
					},
					fail: (err) => {
						console.log(err)
						self.loading = false
					}
				}, 5000);
			},
			// 再次获取授权
			// 当用户第一次拒绝后再次请求授权
			openConfirm() {
				uni.showModal({
					title: '请求授权当前位置',
					content: '需要获取您的地理位置，请确认授权',
					success: (res) => {
						if (res.confirm) {
							uni.openSetting(); // 打开地图权限设置
						} else if (res.cancel) {
							uni.showToast({
								title: '你拒绝了授权，无法获得周边信息',
								icon: 'none',
								duration: 1000
							})
						}
					}
				});
			},
			// 点击地图位置改变中心位置
			poitap: function(e) {
				console.log(e, "poitap")
				let obj = e.detail
				this.clickAddress = e.detail
				this.currentAddress = {}
				// this.mapRange(obj.latitude, obj.longitude)
				this.toLocation(obj)
				// mapCtx.moveToLocation({
				// 	latitude: obj.latitude,
				// 	longitude: obj.longitude
				// })
			},
			toLocation: function(obj) {
				// self.choosePoitFlag = -1
				// 改变地图中心位置
				const lat = obj.latitude || obj.location.lat
				const lng = obj.longitude || obj.location.lng
				// mapCtx.LatLng(lat, lng)
				mapCtx.moveToLocation({
					latitude: lat,
					longitude: lng
				})
				// 查询中心点范围内的地址
				this.mapRange(lat, lng)
				// 移动标记点并添加动画效果
				// mapCtx.translateMarker({
				// 	markerId: 1,
				// 	autoRotate: true,
				// 	duration: 100,
				// 	destination: {
				// 		latitude: lat,
				// 		longitude: lng,
				// 	},
				// 	animationEnd() {
				// 		console.log('animation end')
				// 	}
				// })
			},
			handleActivate(pois, current) {
				// console.log(pois, current, "pois", "current")
				this.activate = pois.findIndex(item => item.address === current.address)
			},
			// 查询地址范围
			mapRange(latitude, longitude) {
				console.log(latitude, longitude, "latitude,longitude")
				let promise = new Promise(function(resolve, reject) {
					// 调用接口
					qqmapsdk.reverseGeocoder({
						location: {
							latitude: latitude,
							longitude: longitude
						},
						get_poi: 1,
						poi_options: 'policy=2;radius=3000;page_size=20;page_index=' + self.pageIndex,
						success: function(res) {
							if (!self.currentAddress.address) {
								self.current = res
								self.handleFilter(res)
							}
							console.log('self.currentAddress', self.currentAddress)
							self.handleActivate(res.result.pois, self.currentAddress)
							if (res.result.pois) {
								self.poitList = [...res.result.pois]
								if (self.tapOpitItem) {
									self.poitList.map((poitTime, index) => {
										if (poitTime.title == self.tapOpitItem.title) {
											console.log(index)
											self.choosePoitFlag = index
										}
									})
								}
							}
							resolve(res)
						},
						fail: function(res) {
							uni.showToast({
								icon: 'none',
								title: '获取地址失败，请点击地图选择地址'
							})
							// tools.showToast(res)
							console.log(res, "res")
							reject(res)
						}
					});
				})
				console.log(self.tapOpitItem)
				console.log(self.poitList)
				return promise
			},
			//搜索地址
			search: function(e) {
				self.searchKey = e.detail.value
				if (self.searchKey) {
					self.empty = true
					self.choosePoitFlag = -1
					self.poitList = []
					self.pageIndex = 1
				} else {
					self.empty = false
					self.IsOption = false
					self.getLocationInfo();
					self.poitList = []
				}
				self.searchData = []
				var location = self.latitude + "," + self.longitude
				self.mapSearch(self.searchKey, location).then(res => {
					self.searchData = res.data
					if (self.searchKey && self.searchData.length) {
						self.IsOption = true
					} else {
						self.IsOption = false
					}
				}, error => {
					// self.$api.msg('请求失败')
					// console.log(error,"aaaaaaaaaaa");
				})

			},
			mapSearch(keyword, location) {
				let promise = new Promise(function(resolve, reject) {
					// 调用接口
					qqmapsdk.getSuggestion({
						keyword: keyword, //搜索关键词
						// auto_extend: 1,
						// location: location, //设置周边搜索中心点
						success: function(res) {
							resolve(res)
						},
						fail: function(res) {
							reject(res)
						}
					});
				})
				return promise

			},
			// 清空搜索框
			closeCircle() {
				self.searchData = []
				self.searchKey = ''
				self.empty = false
				self.IsOption = false
				self.choosePoitFlag = -1
				self.poitList = []
				self.pageIndex = 1
				self.getLocationInfo();
			},
			// 选择搜索地址
			tapOption(item) {
				console.log(item)
				this.searchKey = ''
				this.tapOpitItem = item
				this.IsOption = false
				let obj = {
					latitude: item.location.lat,
					longitude: item.location.lng
				}
				this.toLocation(obj)
				this.currentAddress = item
			},
			// 上拉加载
			moreMessage() {
				self.pageIndex += 1;
				self.mapRange(self.latitude, self.longitude);
			},
			handleSelect(i) {
				this.activate = i
				this.currentAddress = this.poitList[i]
				this.currentAddress.city = this.currentAddress.ad_info.city
				this.currentAddress.district = this.currentAddress.ad_info.district
				this.latitude = this.currentAddress.location.lat;
				this.longitude = this.currentAddress.location.lng;
				this.toLocation(this.currentAddress)
			},
			handleFilter(obj) {
				console.log("self.currentAddress")
				console.log(obj)
				const p = obj.result.pois || []

				const a = self.clickAddress?.address || ''

				p.forEach(item => {
					if (item.address === a) {
						console.log('item', item)
						self.currentAddress = item
					}
				})
				if (!self.currentAddress.address) {
					p.forEach(item => {
						if (item.address == a) {
							console.log(111,item)
							self.currentAddress = item
						}
					})
					if (!self.currentAddress.address) {
						console.log(222,obj.result.pois[0])
						self.currentAddress = obj.result.pois[0]
					}
				}
				self.currentAddress.city = self.currentAddress.ad_info.city
				self.currentAddress.district = self.currentAddress.ad_info.district
				console.log('currentAddress', self.currentAddress)
				console.log(123)
			},
			handleGoBack() {
				console.log(self.currentAddress, "self.currentAddress")
				// uni.$emit('isRefresh', JSON.stringify(self.currentAddress))
				// uni.navigateBack({
				// 	delta: 1
				// })
				// 是否在允许地址 字典 allow_city
				// console.log(this.allowCity)
				if (this.allowCity) {
					const city = this.currentAddress.city
					if (this.allowCity.indexOf(city) == -1) {
						return uni.showToast({
							title: '该地区暂未开放！',
							icon: 'none'
						})
					}
				}
				if (!this.currentAddress.id) return uni.showToast({
					title: '请选择一个地址！',
					icon: 'none'
				})
				this.$emit('selectedAddr', this.currentAddress)
				this.close()
			}
		}
	}
</script>

<style scoped lang="scss">
	::v-deep.rotate-circle {
		display: none;
	}

	.content {
		width: 100%;
	}

	.page-section-gap {
		position: relative;

		.center-icon {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-25rpx, -80rpx);
			z-index: 9;

			// width: 50rpx;
			// height: 50rpx;
			.pst-c {
				width: 50rpx;
				height: 50rpx;
				background-color: #fff;
				border: 15rpx solid #0BCA89;
				border-radius: 50%;
				position: relative;

				.pst-l {
					position: absolute;
					height: 50rpx;
					bottom: -50rpx;
					width: 8rpx;
					left: 9rpx;
					background: #0BCA89;
				}
			}
		}
	}

	.address {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		font-size: 14px;
		color: #808080;
	}

	.flexBox {
		background: #ffffff;
		padding: 18rpx 32rpx;

		.search-warp {
			display: flex;
			background: #F5F7FA;
			padding: 12rpx 20rpx;
			border-radius: 32rpx;

			.search {
				display: flex;
				align-items: center;
				width: 100%;
				flex: 1;
			}

			.area {
				display: flex;
				align-items: center;
				margin-right: 16rpx;
				border-right: 2rpx solid #BABFC9;

				.triangle {
					margin: 0 24rpx 0 18rpx;
					position: relative;
					top: 6rpx;
					width: 0;
					height: 0;
					border-top: 10rpx solid;
					border-right: 10rpx solid transparent;
					border-left: 10rpx solid transparent;
					border-bottom: 10rpx solid transparent;
				}
			}
		}
	}

	.option {
		line-height: 45rpx;
		position: fixed;
		z-index: 9999;
	}

	.column_item {
		padding: 10upx 40rpx;
		/* height: 60rpx; */
		overflow: hidden;
		margin: 0rpx auto;
		background-color: #fff;
		text-overflow: ellipsis;
		white-space: nowrap;
		border-bottom: 2upx solid #ccc;
	}

	.column_item:active {
		background-color: #8F8F94;
	}

	.select-adderss {
		// height: 172rpx;
		background: #FFFFFF;
		box-shadow: 0rpx 0rpx 32rpx 0rpx rgba(0, 0, 0, 0.08);
		border-radius: 16rpx;
		display: flex;
		align-items: center;
		padding: 24rpx 32rpx;
	}

	.s-a-info {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.s-a-but {
		width: 160rpx;
		height: 64rpx;
		background: #0BCA89;
		border-radius: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #ffffff;
	}

	.text-gray {
		font-size: 18px;
	}

	.select-wrap {
		background: #ffffff;
		padding: 32rpx;
		border-radius: 24rpx 24rpx 0rpx 0rpx;
		box-shadow: 0rpx 0rpx 32rpx 0rpx rgba(0, 0, 0, 0.08);
	}

	.list-wrap {
		margin-top: 32rpx;
	}

	.list {
		display: flex;
		border-bottom: #90949E 1rpx solid;
	}

	.info {
		display: flex;
		flex-direction: column;
		margin-left: 16rpx;
	}

	.l-i-title {
		font-weight: 600;
		line-height: 40rpx;
	}

	.l-i-detail {
		line-height: 34rpx;
	}

	.simple-dots {
		width: 32rpx;
		height: 32rpx;
		background: #FFFFFF;
		border: 1rpx solid #BABFC9;
		position: relative;
		top: 6rpx;
		border-radius: 50%;
	}

	.dots {
		width: 32rpx;
		/* 圆的宽度 */
		height: 32rpx;
		/* 圆的高度 */
		background-color: #FFFFFF;
		/* 圆的背景颜色 */
		border-radius: 50%;
		/* 圆的半径，使其形状为圆形 */
		position: relative;
		/* 相对定位，以便在其中放置小点 */
		display: flex;
		align-items: center;
		/* 使小点垂直居中 */
		justify-content: center;
		/* 使小点水平居中 */
		border: #E60012 1rpx solid;
		top: 6rpx;
	}

	.dots::after {
		content: '';
		/* 伪元素的内容为空 */
		width: 16rpx;
		/* 小点的宽度 */
		height: 16rpx;
		/* 小点的高度 */
		background-color: #E60012;
		/* 小点的背景颜色 */
		border-radius: 50%;
		/* 小点的半径，使其形状为圆形 */
		position: absolute;
		/* 绝对定位，以便可以自由移动到圆的中心 */
		top: 50%;
		/* 小点的顶部与圆的中心对齐 */
		left: 50%;
		/* 小点的左侧与圆的中心对齐 */
		transform: translate(-50%, -50%);
		/* 小点相对于圆形图标居中 */
	}

	.list {
		padding: 32rpx 0
	}

	.s-a-t2 {
		margin: 8rpx 0;
	}

	.f-c-6 {
		color: #62636C;
	}
</style>